/*
 * @Author: gxl
 * @email: 1515533507@qq.com
 * @Date: 2021-08-17 19:35:11
 * @LastEditTime: 2022-04-09 22:15:19
 * @FilePath: \blog_web\src\request\index.js
 */

// 导入axios
import axios from 'axios'
//导入获取授权字段的
import db from '@/util/localstorage.js'

// 导入
import { Message, MessageBox } from 'element-ui'

// const BASE_RUL = 'http://127.0.0.1:8000'
// const BASE_RUL = process.env.VUE_APP_BASE_API
const BASE_RUL = 'http://106.52.230.201:8000'
const TIMEOUT = 3 * 1000

const service = axios.create({
  headers: {
    Accept: '*/*'
  },
  baseURL: BASE_RUL,
  timeout: TIMEOUT,
  responseType: 'json'
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    let _config = config
    const token = db.get('token')
    token && (_config.headers.common['authorization'] = `Bearer ${token}`)
    // try {
    //   const expireTime = getExpireTime()
    //   if (expireTime) {
    //     const left = expireTime - new Date().getTime()
    //     const refreshToken = getRefreshToken()
    //     if (left < checkRegion && refreshToken) {
    //       _config = queryRefreshToken(_config, refreshToken)
    //     } else {
    //       if (getToken()) {
    //         _config.headers['Authorization'] = 'bearer ' + getToken()
    //       }
    //     }
    //   }
    // } catch (e) {
    //   console.error(e)
    // }
    return _config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 相应拦截器
service.interceptors.response.use(
  (config) => {
    return config.data
  },
  (error) => {
    if (error.response) {
      const errorMessage =
        error.response.data === null
          ? '系统内部异常，请联系网站管理员'
          : error.response.data.message
      switch (error.response.status) {
        case 404:
          Message({
            message: '很抱歉，资源未找到',
            type: 'error',
            duration: messageDuration
          })
          break
        case 403:
          Message({
            message: '很抱歉，您暂无该操作权限',
            type: 'error',
            duration: messageDuration
          })
          break
        case 401:
          Message({
            message: '很抱歉，认证已失效，请重新登录',
            type: 'error',
            duration: messageDuration
          })
          break
        default:
          if (errorMessage === 'refresh token无效') {
            MessageBox.alert('登录已过期，请重新登录', '温馨提示', {
              confirmButtonText: '确定',
              showClose: false,
              callback: (action) => {
                router.push('/login')
              }
            })
          } else {
            Message({
              message: errorMessage,
              type: 'error',
              duration: messageDuration
            })
          }
          break
      }
    }
    return Promise.reject(error)
  }
)

const request = {
  get(url, params) {
    let _params
    if (Object.is(params, undefined)) {
      _params = ''
    } else {
      _params = '?'
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`
        }
      }
    }
    return service.get(`${url}${_params}`)
  },
  post(url, params) {
    console.log('携带从参数为', url, params)
    return service.post(url, params, {
      // transformRequest: [(params) => {
      //   return tansParams(params)
      //   // return params
      // }],
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  upload(url, params) {
    return service.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

export default request
